package auth

import (
	"context"
	"database/sql"
	"regexp"
	"time"

	"portal/internal/common"
	"portal/internal/errorx"
	"portal/internal/svc"
	"portal/internal/types"
	"portal/model"
	"portal/tools/encryption"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

type EnrollLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	accountModel model.AwAccountsModel
}

func NewEnrollLogic(ctx context.Context, svcCtx *svc.ServiceContext) *EnrollLogic {
	return &EnrollLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		accountModel: model.NewAwAccountsModel(svcCtx.Orm),
	}
}

func (l *EnrollLogic) Enroll(req *types.EnrollReqest) (resp *types.CommonResponse, err error) {
	// todo: add your logic here and delete this line
	isUname := regexp.MustCompile(common.UserFormat).Match([]byte(req.Username))
	isPword := regexp.MustCompile(common.PasswordFormat).Match([]byte(req.Password))
	if !isUname || !isPword {
		return &types.CommonResponse{
			Status: 500,
			Msg: "账号密码格式不正确",
		},nil
	}

	if len(req.Mail) > 0 {
		isMail := regexp.MustCompile(common.EmailFormat).Match([]byte(req.Mail))
		if !isMail {
			return &types.CommonResponse{
				Status: 500,
				Msg: "邮箱格式不正确",
			},nil
		}
	}
	_,err = l.accountModel.SelectOneByUname(l.ctx,nil,req.Username)
	if err != sqlx.ErrNotFound {
		return &types.CommonResponse{
			Status: 500,
			Msg: "该账号已被注册",
		},nil
	}

	now := time.Now().Unix()

	account := &model.AwAccounts{
		Username: req.Username,
		Password: encryption.EncryNoTimeSha256(req.Password,l.svcCtx.Config.JwtSecret),
		CreatedAt: now,
		UpdatedAt: now,
		RoleId: sql.NullInt64{Int64: 3},
		Name: req.Name,
		Department:req.Department,
		Avatar: req.Avatar,
		Sex: int64(req.Sex),
		Mail: req.Mail,
		Introduction: req.Introduction,
	}

	res,err := l.accountModel.Insert(l.ctx,account)
	if err != nil {
		return nil,errorx.NewBizError(500,err.Error())
	}

	accountId,_ := res.LastInsertId()

	return &types.CommonResponse{
		Status: 200,
		Msg: "账号创建成功",
		Data: accountId,
	},nil
}
